"""
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    created by lane.chang on '10/11/2023'
    由yuwei.li于26/03/2025自cariabot复制至leto
    comment: 阿里云存储桶相关
"""
import uuid
import requests
import datetime
import oss2
from urllib.parse import urlparse, quote


class Oss(object):

    def __init__(self, access_key='LTAI5tPN6E81hSxw3qaDDr7Z',
                 access_secret='yg7X0MRdK7josM9deAQnVXMiZyUQbF',
                 bucket_name='roboland-ai',
                 end_point='https://oss-cn-shenzhen.aliyuncs.com'):

        auth = oss2.Auth(access_key, access_secret)
        self.end_point = end_point
        self.bucket_name = bucket_name
        self.bucket = oss2.Bucket(auth, end_point, bucket_name, connect_timeout=30)

    def upload_file_simple(self, object_name, local_file):
        """ 简单上传文件
        :param object_name: 上传oss文件名称
        :param local_file: 本地文件全路径名称
        :return:
            - 文件的存储桶链接
        """
        # 设置元信息头
        headers = {
            'Content-Disposition': 'attachment'
        }
        # 简单上传
        result = self.bucket.put_object_from_file(object_name, local_file, headers=headers)

        if result.status != 200:
            raise Exception('文件上传失败')

    def upload_file(self, object_name, bytes_file):
        """ 上传文件
        :param object_name: 上传oss文件名称
        :param bytes_file: 文件字节流
        :return:
            - 文件的存储桶链接
        """
        # 设置元信息头
        headers = {
            'Content-Disposition': 'attachment'
        }
        # object_name = quote(object_name)
        result = self.bucket.put_object(object_name, bytes_file, headers=headers)
        print(result.resp.request_id)
        if result.status != 200:
            raise Exception(f'文件上传失败。request_id: {result.resp.request_id}')
        return self.get_url(object_name)

    def get_sign_url(self, object_name, expires=60):
        """ 生成下载文件的签名url
        :param object_name: 下载对象名称
        :param expires: 有效时间, 单秒
        :return:
        """
        return self.bucket.sign_url('GET', object_name, expires=expires)

    def get_url(self, object_name):
        """ 生成下载文件的url-不含签名
        :param object_name: 下载对象名称
        :param expires: 有效时间, 单秒
        :return:
        """
        agreement = self.end_point.split(':')[0]
        domain = urlparse(self.end_point).hostname

        if not self.object_exists(object_name):
            raise Exception('文件不存在')

        return f'{agreement}://{self.bucket_name}.{domain}/{object_name}'

    def object_exists(self, object_name):
        """ 判断对象文件是否存在
       :param object_name: 下载对象名称
       :return:
       """
        return self.bucket.object_exists(object_name)

    def delete_object(self, object_name):
        """ 删除单个对象文件
        :param object_name:
        :return:
        """
        if self.object_exists(object_name):
            self.bucket.delete_object(object_name)
        else:
            print(f'{object_name}文件在OSS中不存在')

    def create_folder(self, name):
        """ oss创建目录
        :param name: 存储桶的目录(../xx)
        :return:
        """
        if not name.endswith('/'):
            name += '/'

        self.bucket.put_object(name, '')

    def remove_folder(self, name):
        """ oss删除目录
        :param name: 存储桶的目录(../xx)
        :return:
        """
        if not name.endswith('/'):
            name += '/'

        self.bucket.delete_object(name)

    def download_file(self, object_name, local_file):
        """
        :param oss_path:
        :param get_object_to_file:
        :return:
        """
        self.bucket.get_object_to_file(object_name, local_file)


if __name__ == "__main__":

    oss = Oss(bucket_name='roboland-ai', end_point='https://oss-cn-shenzhen.aliyuncs.com')

    # url = 'https://shipping-file.oss-cn-shenzhen.aliyuncs.com/file/20240508/5997e0c9-6e2a-4581-bb4a-57a6d81124f2_数字人.png'
    # res = requests.get(url)
    #
    # # 设置元信息头
    # headers = {
    #     'Content-Disposition': 'attachment'
    # }
    # file_extension = url.split('.')[-1]
    # object_name = f'assichat/file/{datetime.datetime.now().strftime("%Y%m%d")}/{str(uuid.uuid4())}_{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}.{file_extension}'
    # oss.bucket.put_object(object_name, res.content, headers=headers)
    #
    # print(oss.get_url(object_name))
    # local_file = '/Users/chang/carebot/icon/es-1702025009890.jpg'
    #
    # oss.download_file(object_name, local_file)
    with open('C:\\Users\\yuwei.li2\\Downloads\\健康评估_康养.png', 'rb') as f:
        url =oss.upload_file('cariabot/icon/上传测试3.png', f.read())
        print(url)



